package cn.uniquesoft.controller.api;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 作者: zyx 2017年12月1日 上午10:09:19 邮件: zmmqq00@163.com 描述: 轮播下载
 */
@RestController
@RequestMapping(value = "/api/lb")
public class LBController {

    private static Logger Log = Logger.getLogger(LBController.class);
    @Value("${shuffling.save.dir}")
    private String shufflingSaveDir = "";

    @Value("${image.save.dir}")
    private String imageSaveDir = "";

    @RequestMapping(value = "/down/{appType}")
    public String downFile(@PathVariable String appType, HttpServletRequest request, HttpServletResponse response) {
        try {
            String realPath = shufflingSaveDir;
            String fileName = "bst_shuffling.json";
            File file = new File(realPath, fileName);
            if (!file.exists()) {
                return "";
            }
            String strJson = "";
            if (file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                    strJson += lineTxt;
                }
                br.close();
                return strJson;
            } else {
                Log.info("文件不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.info("文件读取错误!");
        }
        return "";
    }


    //下载图片文件
    @RequestMapping(value = "/image/{type}/{fileName}")
    public void downImage(@PathVariable String fileName, @PathVariable String type, HttpServletRequest request, HttpServletResponse response) {
        String realPath = imageSaveDir;
        if (realPath == null || fileName == null || realPath.length() == 0 || fileName.length() == 0) {
            return;
        }
        Log.info("请求" + realPath + "" + fileName + "." + type);
        File file = new File(realPath, fileName + "." + type);
        if (!file.exists()) {
            Log.info("文件不存在" + realPath + "" + fileName + "." + type);
            return;
        }
        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            response.setContentType("image/png");
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //下载图片文件
    @RequestMapping(value = "/image2/{fileName}")
    public void downImage2(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) {
        String realPath = imageSaveDir;
        if (realPath == null || fileName == null || realPath.length() == 0 || fileName.length() == 0) {
            return;
        }
        File file = new File(realPath, fileName);
        if (!file.exists()) {
            return;
        }
        Log.info("下载文件:" + realPath + "" + fileName);
        try {
            // 设置响应头:内容处理方式 → attachment(附件,有为下载,没有为预览加载) →指定文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            // 从服务器上下载图片,要找到图片在服务器中的真实位置
            //String realPath = request.getServletContext().getRealPath("/img");
            // 从服务器上读入程序中
            InputStream fileInputStream = new FileInputStream(realPath + "\\" + fileName);
            // 从程序中写出下载到客户端
            OutputStream outputStream = response.getOutputStream();
            // copy以及关闭流资源
            IOUtils.copy(fileInputStream, outputStream);
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //下载图片文件
    @RequestMapping(value = "/image1/{fileName}")
    public void downImage1(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) {
        String realPath = imageSaveDir;
        if (realPath == null || fileName == null || realPath.length() == 0 || fileName.length() == 0) {
            return;
        }
        File file = new File(realPath, fileName);
        if (!file.exists()) {
            return;
        }
        Log.info("下载文件:" + realPath + "" + fileName);
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            FileInputStream inputStream = new FileInputStream(file);
            response.setHeader("Content-Length", String.valueOf(file.length()));
            //byte[] bos = IOUtils.read(inputStream);
            byte[] bos = new byte[inputStream.available()];
            inputStream.read(bos);
            OutputStream out = null;
            out = response.getOutputStream();
            out.write(bos);
            out.flush();
            out.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
